package com.service.api;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class CacheManager_app {
	private static CacheManager_app manager;
	
	private ClientBootstrap bootstrap;
	
	public Map<Integer,BaiduApiServer> appMap = null;

	/**
	 * 采用单例模式构建缓存结构
	 * @return CacheManager
	 */
	public static CacheManager_app instance() {
		if(manager==null){
			manager = new CacheManager_app();
			manager.appMap = new ConcurrentHashMap<Integer, BaiduApiServer>();
		}
		return manager;
	}

	public ClientBootstrap getBootstrap() {
		if (bootstrap == null){
	    	NioClientSocketChannelFactory nioscf = new NioClientSocketChannelFactory(
	    			Executors.newCachedThreadPool(),
	    			Executors.newCachedThreadPool());
	    	
	    	bootstrap = new ClientBootstrap(nioscf);
			bootstrap.setPipelineFactory(new HttpClientPipelineFactory(false));
            
			return bootstrap;
		}
		else{
			return bootstrap;
		}
	}
	
	public Channel getActiveChannel(String ip,int port) throws Exception {

		ChannelFuture f = getBootstrap().connect(
				new InetSocketAddress(ip, port));	
		
		if(!f.awaitUninterruptibly().isSuccess()){
			throw new Exception("connect err" + "(ip =" + ip + " port="+port +")");
		}			
		Channel activeChannel = f.awaitUninterruptibly().getChannel();
		
		return activeChannel;
	}

}
